package com.tt.vtg.exception;

import static com.tt.vtg.exception.ExceptionConstants.*;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionHandlingController {
	/**
	 * catch all exceptions,if not specific exception handler
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public ResponseEntity<ExceptionResponse> catchAllException(Exception ex) {
		ExceptionResponse response = new ExceptionResponse();
		response.setErrorCode(OTHER_ERROR);
		response.setErrorMessage(ex.getMessage());
		return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
	}
	
	@ExceptionHandler(VtgException.class)
	public ResponseEntity<ExceptionResponse> vtgException(VtgException ex) {
		ExceptionResponse response = new ExceptionResponse();
		response.setErrorCode(ex.getErrorCode());
		response.setErrorMessage(ex.getMessage());
		HttpStatus httpStatus=null;
		try {
			httpStatus = HttpStatus.valueOf(ex.getResponseCode());
		} catch (Exception e) {
			httpStatus=HttpStatus.BAD_REQUEST;
		}
		return new ResponseEntity<ExceptionResponse>(response, httpStatus);
	}
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ResponseEntity<ExceptionResponse> httpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex){
		ExceptionResponse response = new ExceptionResponse();
		response.setErrorCode(UNSUPPORTED_METHOD);
		response.setErrorMessage(ex.getMessage());
		return new ResponseEntity<ExceptionResponse>(response, HttpStatus.METHOD_NOT_ALLOWED);
	}
}
